import EventEmitter from 'events';
import SocketIO from 'socket.io';

export class SocketServer extends EventEmitter {
  private io = undefined;

  constructor(app) {
    super();

    if (globalThis.io) {
      throw new Error('socket server already exists')
    }

    this.io = SocketIO(app, {
      path: '',
      pingTimeout: 5000,
      pingInterval: 10000
    });

    this.io.on('connection', (socket) => {
      this.emit('connection', socket);
    });

    globalThis.io = this.io
  }

  /**
   * 向所有客户端广播消息
   * @param event 事件名
   * @param rest rest参数
   */
  emitMessage(event: string, ...rest: any[]) {
    if (this.io) {
      this.io.sockets.emit(event, ...rest);
    }
  }

  /**
   * 向指定房间内客户端广播消息
   * @param roomName 房间名
   * @param event 事件名
   * @param rest rest参数
   */
  emitRoomMessage(roomName: string, event: string, ...rest: any[]) {
    if (this.io) {
      this.io.sockets.to(roomName).emit(event, ...rest);
    }
  }

  /**
   * 向所有客户端广播报错信息
   * @param msg 消息内容
   */
  emitError(msg: string) {
    this.emitMessage('error', msg);
  }

  /**
   * 向所有客户端广播成功信息
   * @param msg 消息内容
   */
  emitSuccess(msg: string) {
    this.emitMessage('success', msg);
  }
}
